package com.rfid.manager;

import android.app.Activity;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.provider.Settings;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;

import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.rfid.a252robot.App;
import com.rfid.a252robot.R;
import com.rfid.a252robot.activity.adapter.LogAdapter;
import com.rfid.common.log.LogUtils;
import com.rfid.common.util.SharedPreferencesUtil;
import com.rfid.mqtt.MqttManager;
import com.shrfid.module_base.entity.TagEntity;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public enum LogViewManager {

    INSTANCE;

    View mView;
    WindowManager mWindowManager;
    WindowManager.LayoutParams layoutParams;
    List<String>mData = new ArrayList<>();
    LogAdapter mAdapter = new LogAdapter(mData);
    RecyclerView recyclerView;
    Handler handler = new Handler();

    public void init(Context context) {
        boolean log = SharedPreferencesUtil.getInstance().getBoolean("test_mode");
        if (!log) {
            return;
        }
        if (mView != null) {
            return;
        }
        mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        layoutParams = new WindowManager.LayoutParams();
        layoutParams.width = 500;
        layoutParams.height = 700;
        layoutParams.x = 0;
        layoutParams.y = 300;
        layoutParams.gravity = Gravity.LEFT|Gravity.TOP;
//        layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        }
        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        mView = LayoutInflater.from(context).inflate(R.layout.log_layout,null);
        View x = mView.findViewById(R.id.x);
        x.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferencesUtil.getInstance().putBoolean("test_mode",false);
                hide();
            }
        });
        CheckBox showTag = mView.findViewById(R.id.show_tag);
        CheckBox showLog = mView.findViewById(R.id.show_log);
        CheckBox robotLog = mView.findViewById(R.id.robot_log);
        showTag.setChecked(SharedPreferencesUtil.getInstance().getBoolean("show_tag"));
        showLog.setChecked(SharedPreferencesUtil.getInstance().getBoolean("show_log"));
        robotLog.setChecked(SharedPreferencesUtil.getInstance().getBoolean("robot_log"));
        showTag.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                SharedPreferencesUtil.getInstance().putBoolean("show_tag",isChecked);
            }
        });
        showLog.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                SharedPreferencesUtil.getInstance().putBoolean("show_log",isChecked);
            }
        });
        robotLog.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                SharedPreferencesUtil.getInstance().putBoolean("robot_log",isChecked);
            }
        });
        LogUtils.setCallBack(new LogUtils.CallBack() {
            @Override
            public void onLog(String tag,String log) {
                boolean robot = SharedPreferencesUtil.getInstance().getBoolean("robot_log");
                if (SharedPreferencesUtil.getInstance().getBoolean("show_log")) {
                    if (robot) {
                        add(log);
                    } else if (!MqttManager.TAG.equals(tag)) {
                        add(log);
                    }
                } else if(robot) {
                    if (MqttManager.TAG.equals(tag)) {
                        add(log);
                    }
                }
            }
        });
        recyclerView = mView.findViewById(R.id.recyclerView);
        recyclerView.addItemDecoration(new DividerItemDecoration(context,DividerItemDecoration.VERTICAL));
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.setAdapter(mAdapter);
    }

    public void show() {
        if (mView == null) {
            return;
        }
        boolean log = SharedPreferencesUtil.getInstance().getBoolean("test_mode");
        if (!log) {
            return;
        }
        if (mView.getParent() != null) {
            add("test");
            return;
        }
        mData.clear();
        mWindowManager.addView(mView,layoutParams);
    }

    public void add(List<TagEntity> tags) {
        boolean log = SharedPreferencesUtil.getInstance().getBoolean("test_mode");
        if (!log) {
            return;
        }
        for (TagEntity tag:tags) {
            mData.add(0,tag.getUid() + "\n" + tag.getBookNo());
        }
        handler.post(new Runnable() {
            @Override
            public void run() {
                mAdapter.notifyDataSetChanged();
                recyclerView.smoothScrollToPosition(0);
            }
        });
    }

    public void add(String msg) {
        boolean log = SharedPreferencesUtil.getInstance().getBoolean("test_mode");
        if (!log) {
            return;
        }
        mData.add(0,msg);
        handler.post(new Runnable() {
            @Override
            public void run() {
                mAdapter.notifyDataSetChanged();
                recyclerView.smoothScrollToPosition(0);
            }
        });
    }

    public void hide() {
        if (mView == null) {
            return;
        }
        mWindowManager.removeView(mView);
    }

    public boolean checkFloatPermission(Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT)
            return true;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            try {
                Class cls = Class.forName("android.content.Context");
                Field declaredField = cls.getDeclaredField("APP_OPS_SERVICE");
                declaredField.setAccessible(true);
                Object obj = declaredField.get(cls);
                if (!(obj instanceof String)) {
                    return false;
                }
                String str2 = (String) obj;
                obj = cls.getMethod("getSystemService", String.class).invoke(context, str2);
                cls = Class.forName("android.app.AppOpsManager");
                Field declaredField2 = cls.getDeclaredField("MODE_ALLOWED");
                declaredField2.setAccessible(true);
                Method checkOp = cls.getMethod("checkOp", Integer.TYPE, Integer.TYPE, String.class);
                int result = (Integer) checkOp.invoke(obj, 24, Binder.getCallingUid(), context.getPackageName());
                return result == declaredField2.getInt(cls);
            } catch (Exception e) {
                return false;
            }
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                AppOpsManager appOpsMgr = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
                if (appOpsMgr == null)
                    return false;
                int mode = appOpsMgr.checkOpNoThrow("android:system_alert_window", android.os.Process.myUid(), context
                        .getPackageName());
                return Settings.canDrawOverlays(context) || mode == AppOpsManager.MODE_ALLOWED || mode == AppOpsManager.MODE_IGNORED;
            } else {
                return Settings.canDrawOverlays(context);
            }
        }
    }

    public static final int REQUEST_CODE = 1010;
    public void requestFloatPermission(Activity context){
        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
        intent.setData(Uri.parse("package:" + context.getPackageName()));
        context.startActivityForResult(intent, REQUEST_CODE);
    }

    public void onActivityResult(Activity context,int requestCode, int resultCode, Intent data) {
        if(requestCode == this.REQUEST_CODE) {
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if(!checkFloatPermission(context)){
                        requestFloatPermission(context);
                    }
                }
            },1000);
        }
    }
}
